<template>
  <a-form
    class="w-3/4"
    :model="formRef"
    ref="form"
    size="large"
    @keyup.enter="handleLogin"
  >
    <a-form-item>
      <div class="text-center">
        <div
          class="w-96px h-96px rounded-full bg-primary mx-auto flex-center text-white text-18px"
          v-if="userInfo"
        >
          {{ userInfo.name }}
        </div>
        <img v-else w-96px h-96px :src="avatarPng" alt="" />
      </div>
    </a-form-item>

    <a-form-item name="username" :rules="phoneRules">
      <a-input
        placeholder="手机号或邮箱"
        size="large"
        v-model:value="formRef.username"
      ></a-input>
    </a-form-item>

    <a-form-item
      v-if="formRef.type == 'password'"
      name="password"
      :rules="{
        required: true,
        message: '请输入密码',
        trigger: 'blur',
      }"
    >
      <a-input-password
        placeholder="密码"
        size="large"
        v-model:value="formRef.password"
      ></a-input-password>
    </a-form-item>

    <a-form-item
      v-if="formRef.type == 'sms'"
      name="verify_code"
      :rules="{
        required: true,
        message: '请输入',
      }"
    >
      <a-input-group compact>
        <a-input
          v-model:value="formRef.verify_code"
          style="width: 50%"
          placeholder="验证码"
        ></a-input>
        <a-button disabled v-if="isSending" class="w-1/2">
          发送中({{ timeRef }})
        </a-button>
        <a-button type="primary" @click.prevent="sendMsg" v-else class="w-1/2">
          获取验证码
        </a-button>
      </a-input-group>
    </a-form-item>

    <div class="flex justify-between mb-4">
      <a
        type="link"
        @click="formRef.type = 'sms'"
        v-if="formRef.type == 'password'"
      >
        验证码登录
      </a>
      <a
        type="link"
        @click="formRef.type = 'password'"
        v-if="formRef.type == 'sms'"
      >
        密码登录
      </a>
      <a type="link" @click="emits('changeType', 'ResetPwd')">忘记密码</a>
    </div>

    <a-form-item :wrapper-col="{ span: 0 }">
      <a-button type="primary" w-full size="large" @click="handleLogin">
        登录
      </a-button>
    </a-form-item>

    <div class="text-center">
      没有账号？
      <a @click="emits('changeType', 'RegisterForm')">立即注册</a>
    </div>
  </a-form>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { set_user_token } from '@/utils/storage';
import { userLogin } from '@/api/common';
import avatarPng from '@/assets/default_avatar.png';
import md5 from 'md5';

const emits = defineEmits(['changeType']);

const formRef = reactive({
  username: '',
  password: '',
  type: 'password',
  verify_code: '',
});

const form = ref();
const router = useRouter();

const phoneRules = [
  {
    validator: (_rule, value) => {
      if (!value) return Promise.reject('请输入手机号');
      return Promise.resolve();
      if (/^1[3456789]\d{9}$/.test(value)) {
        return Promise.resolve();
      } else {
        return Promise.reject('请输入正确的手机号');
      }
    },
  },
];

const { isSending, send, timeRef } = useSms();
const sendMsg = () => {
  form.value.validate(['username']).then(() => {
    send({
      phone: formRef.username,
      smsType: 'Login',
    });
  });
};

const handleLogin = () => {
  form.value.validate().then(async () => {
    let res;
    if (formRef.type == 'password') {
      res = await userLogin({
        grant_type: 'password',
        password: md5(formRef.password),
        username: formRef.username,
        client_id: 'merger-bed',
      });
    } else if (formRef.type == 'sms') {
      res = await userLogin({
        grant_type: 'sms',
        verify_code: formRef.verify_code,
        username: formRef.username,
        client_id: 'merger-bed',
      });
    }
    if (res.code == 'ok') {
      set_user_token(res.data.access_token);
      router.push({ path: '/' });
    } else {
      // message.error(res.message);
    }
  });
};

const userInfo = st.get('user_info');
</script>
